package com.promise.jokerdream.ui.settings

import androidx.compose.foundation.layout.*
import androidx.compose.foundation.clickable
import androidx.compose.material3.*
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.dp
import com.promise.jokerdream.database.entity.ChaosWarGameConfigEntity
import com.promise.jokerdream.model.ChaosWarMapping
import com.promise.jokerdream.ui.components.SettingCard
import com.promise.jokerdream.ui.components.MultiSelectHashtagBottomSheet
import com.promise.jokerdream.ui.components.SelectionRow
import com.promise.jokerdream.ui.theme.AppSpacing

/**
 * 乱斗设置卡片
 */
@Composable
fun ChaosWarSettingCard(
    config: ChaosWarGameConfigEntity,
    onChaosWarChange: (Boolean) -> Unit,
    onTasksChange: (List<String>) -> Unit,
    modifier: Modifier = Modifier,
    onExecuteClick: (() -> Unit)? = null
) {
    var showBottomSheet by remember { mutableStateOf(false) }
    
    SettingCard(
        title = "乱斗",
        description = "选择保留的任务，领奖前不刷新",
        checked = config.enabledSetting,
        onCheckedChange = onChaosWarChange,
        modifier = modifier,
        onExecuteClick = onExecuteClick,
        content = {
            if (config.enabledSetting) {
                Column(
                    modifier = Modifier.fillMaxWidth()
                ) {
                    // 转换 selectedTasks: String -> List<String>
                    val selectedTasks = if (config.selectedTasks.isEmpty()) {
                        emptyList()
                    } else {
                        config.selectedTasks.split(",").map { it.trim() }
                    }
                    // 任务选择区域
                    SelectionRow(
                        label = "选择任务：",
                        selectedText = if (selectedTasks.isEmpty()) "未选择" else "已选择${selectedTasks.size}项",
                        onClick = { showBottomSheet = true }
                    )
                }
            }
        }
    )

    // 任务选择底部弹窗
    if (showBottomSheet) {
        // 转换 selectedTasks: String -> List<String>
        val selectedTasks = if (config.selectedTasks.isEmpty()) emptyList() else config.selectedTasks.split(",").map { it.trim() }
        MultiSelectHashtagBottomSheet(
            title = "选择乱斗任务",
            initialTags = selectedTasks,
            placeholder = "输入任务名称，回车添加",
            recommendedTags = ChaosWarMapping.tasks,
            onCancel = { showBottomSheet = false },
            onComplete = { tasks ->
                onTasksChange(tasks)
                showBottomSheet = false
            },
            onDismiss = { showBottomSheet = false }
        )
    }
}
